<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option
          v-for="item in employeesList"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="submit">确定</el-button>
      <el-button size="small" @click="$emit('close')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployees } from '@/api/employees'
import { addDepartment, departmentDatil, updateDepartment } from '@/api/departments'
export default {
  name: 'VueHrDeptDialog',
  props: {
    // 接收父组件传过来的值
    id: {
      type: String,
      required: true
    },
    // 接收父组件穿过来的新增或编辑的状态
    isEdit: {
      type: Boolean,
      required: true
    },
    orignList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 自定义校验部门编码的唯一性
    const validCode = (rule, value, callback) => {
      let existCode = this.orignList.map(item => item.code)
      // 判断如果是编辑的状态，就排除掉自己的id
      if (this.isEdit) {
        existCode = this.orignList.filter(item => item.id !== this.id).map(item => item.code)
      }
      // console.log(existCode)
      if (existCode.includes(value)) {
        callback(new Error(`部门编码：${value}已存在`))
      } else {
        callback() // 放行
      }
    }
    // 自定义校验部门名称在同级不能重复
    const validName = (rule, value, callback) => {
      // console.log(this.orignList)
      let orignName = this.orignList.filter(item => item.pid === this.id).map(item => item.name)
      // console.log(orignName)
      // 编辑状态下
      if (this.isEdit) {
        const curDepartment = this.orignList.find(item => item.id === this.id)
        const pid = curDepartment.pid
        // 通过pid找到兄弟部门 包括自己
        const brother = this.orignList.filter(item => item.pid === pid)
        orignName = brother.filter(item => item.id !== this.id).map(item => item.name)
      }
      if (orignName.includes(value)) {
        callback(new Error(`部门名称：${value}已存在`))
      } else {
        callback()
      }
    }
    return {
      // 收集表单数据
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1-300个字符', trigger: 'blur' }

        ],
        introduce: [
          { required: true, message: '请输入部门负责人', trigger: 'blur' }
        ]
      },
      employeesList: [] // 负责人列表
    }
  },

  mounted() {

  },
  created() {
    // 新增子部门
    this.loadEmployees()
    // isEdit 是true的状态就是编辑 调用获部门详情的函数
    if (this.isEdit) {
      this.loaddepartmentDatil()
    }
  },
  methods: {
    // 重置表单
    resetForm() {
      // resetFields() 重置表单
      this.$refs.deptForm.resetFields()
    },
    // 获取部门详情
    async loaddepartmentDatil() {
      const res = await departmentDatil(this.id)
      // console.log(res)
      // 编辑状态数据回显到表单
      this.form = res.data
    },
    submit() {
      // 兜底校验
      this.$refs.deptForm.validate(valid => {
        // console.log(valid)
        if (!valid) return
        this.isEdit ? this.doisEdit() : this.doadd()
      })
    },
    // 编辑
    async doisEdit() {
      try {
        const res = await updateDepartment(this.form)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 子传父 在父组件里面进行  渲染列表  关闭弹层
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 新增子部门  单独封装新增的请求在submit()事件中调用
    async doadd() {
      try {
        // 传值的时候发现还需要pid 子组件没有需要父组件传值过来
        // 注意这里请求的数据 需要是一个对象
        const res = await addDepartment({ ...this.form, pid: this.id })
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 子传父 在父组件里面进行  渲染列表  关闭弹层
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取部门负责人
    async loadEmployees() {
      try {
        const res = await getEmployees()
        // console.log(res)
        this.employeesList = res.data
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
